//
//  KATLabelBar.m
//  KATFramework
//
//  Created by Yi Yu on 2018/3/6.
//  Copyright © 2018年 KatApp. All rights reserved.
//

#import "KATLabelBar.h"




@interface KATLabelBar()

///选中的标签
@property(nonatomic,assign) int selectedIndex;

///是否已经加载完成
@property(nonatomic,assign) BOOL isLoaded;

///背景
@property(nonatomic,retain) UIView *background;

///内容
@property(nonatomic,retain) UIScrollView *content;

///标签数组
@property(nonatomic,retain) KATArray<KATLabel *> *labels;

///渐变
@property(nonatomic,retain) CAGradientLayer *gradient;

///数据
@property(nonatomic,retain) KATArray<KATLabelBarData *> *dataArray;

///默认的选中的样式(除字体颜色外和默认样式一样)
@property(nonatomic,copy) KATTextStyle *selectedStyle;

@end



@implementation KATLabelBar


#pragma -mark 类方法

//获取实例(默认样式)
+ (instancetype)labelBarWithFrame:(CGRect)frame
{
    KATLabelBar *bar=[[[self alloc] init] autorelease];
    
    bar.isLoaded=NO;
    
    bar.frame=frame;
    bar.indicator=nil;
    bar.isFilledIndicator=NO;
    bar.indicatorPositionY=frame.size.height*0.86;
    bar.slidingDuration=0.25;
    bar.hasGradientEffect=YES;
    bar.selectedColor=KCOLOR_BLUE;
    bar.padding=16.0;
    bar.margin=12.0;
    
    bar.defaultStyle=[KATTextStyle textStyle];
    bar.defaultStyle.textFont=[UIFont systemFontOfSize:frame.size.height*0.382];
    bar.defaultStyle.textColor=KCOLOR_GRAY;
    bar.defaultStyle.hasUrlStyle=NO;
    
    bar.selectedStyle=bar.defaultStyle;
    bar.selectedStyle.textColor=bar.selectedColor;
    
    bar.dataArray=nil;
    bar.labels=nil;
    
    //背景
    bar.background=[[[UIView alloc] init] autorelease];
    bar.background.backgroundColor=KCOLOR_CLEAR;
    bar.background.frame=bar.bounds;
    [bar addSubview:bar.background];
    
    //内容
    bar.content=[[[UIScrollView alloc] init] autorelease];
    bar.content.frame=bar.background.bounds;
    bar.content.backgroundColor=KCOLOR_CLEAR;
    bar.content.contentSize=bar.bounds.size;
    bar.content.alwaysBounceHorizontal=YES;
    bar.content.showsHorizontalScrollIndicator=NO;
    bar.content.showsVerticalScrollIndicator=NO;
    [bar.background addSubview:bar.content];
    
    //渐变
    bar.gradient=[CAGradientLayer layer];
    bar.gradient.frame=bar.bounds;
    
    //设置渐变颜色方向
    bar.gradient.startPoint=CGPointMake(0.0, 0.5);
    bar.gradient.endPoint=CGPointMake(1.0, 0.5);
    
    //设定颜色组（作为蒙板）
    bar.gradient.colors=@[(__bridge id)[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0].CGColor,(__bridge id)[UIColor whiteColor].CGColor,(__bridge id)[UIColor whiteColor].CGColor,(__bridge id)[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0].CGColor];
    
    //设定颜色分割点
    bar.gradient.locations=@[@(0.0f),@(bar.margin/bar.bounds.size.width),@(1.0-bar.margin/bar.bounds.size.width),@(1.0f)];
    
    bar.eventDelegate=nil;
    
    bar.isLoaded=YES;
    
    return bar;
}



#pragma -mark 对象方法


//设置frame
- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    if(_isLoaded)
    {
        _background.frame=self.bounds;
        _content.frame=_background.bounds;
        _gradient.locations=@[@(0.0f),@(_margin/_background.bounds.size.width),@(1.0-_margin/_background.bounds.size.width),@(1.0f)];
        
        [self updateView];
    }
}


//设置内间距
- (void)setPadding:(double)padding
{
    _padding=padding;
    
    if(_isLoaded)
    {
        [self updateView];
    }
}


//设置外边距
- (void)setMargin:(double)margin
{
    _margin=margin;
    
    if(_isLoaded)
    {
        [self updateView];
    }
}


//设置默认的标签样式
- (void)setDefaultStyle:(KATTextStyle *)defaultStyle
{
    if(_defaultStyle!=defaultStyle)
    {
        [_defaultStyle release];
        _defaultStyle=[defaultStyle retain];
        
        if(_isLoaded)
        {
            self.selectedStyle=_defaultStyle;
            _selectedStyle.textColor=_selectedColor;
            
            [self updateView];
        }
    }
}


//设置默认的指示器颜色
- (void)setselectedColor:(UIColor *)selectedColor
{
    if(_selectedColor!=selectedColor)
    {
        [_selectedColor release];
        _selectedColor=[selectedColor retain];
        
        if(_isLoaded)
        {
            _selectedStyle.textColor=_selectedColor;
            
            [self updateView];
        }
    }
}


//设置是否具有渐变效果
- (void)setHasGradientEffect:(BOOL)hasGradientEffect
{
    _hasGradientEffect=hasGradientEffect;
    
    if(_isLoaded)
    {
        [self updateView];
    }
}



//设置指示器中心点y轴坐标
- (void)setIndicatorPositionY:(double)indicatorPositionY
{
    _indicatorPositionY=indicatorPositionY;
    
    if(_isLoaded)
    {
        [self updateView];
    }
}



//设置指示器是否填充
- (void)setIsFilledIndicator:(BOOL)isFilledIndicator
{
    _isFilledIndicator=isFilledIndicator;
    
    if(_isLoaded)
    {
        [self updateView];
    }
}


//设置指示器
- (void)setIndicator:(KATShape *)indicator
{
    if(_indicator!=indicator)
    {
        [_indicator removeFromSuperlayer];
        
        [_indicator release];
        _indicator=[indicator retain];
        
        if(_isLoaded)
        {
            if(_indicator)
            {
                [_content.layer addSublayer:_indicator];
            }
            
            [self updateView];
        }
    }
}


//设置数据
- (void)setDataArray:(KATArray<KATLabelBarData *> *)dataArray
{
    if(_dataArray!=dataArray)
    {
        [_dataArray release];
        _dataArray=[dataArray retain];
        
        _selectedIndex=-1;
        
        [self updateView];
    }
}


//获取选中的数据
- (KATLabelBarData *)selectedData
{
    if(_dataArray && _selectedIndex>=0 && _selectedIndex<_dataArray.length)
    {
        return _dataArray[_selectedIndex];
    }
    
    return nil;
}



//更新控件
- (void)updateView
{
    _background.frame=self.bounds;
    _content.frame=_background.bounds;
    _gradient.locations=@[@(0.0f),@(_margin/_background.bounds.size.width),@(1.0-_margin/_background.bounds.size.width),@(1.0f)];
    
    //渐变效果
    if(_hasGradientEffect)
    {
        _gradient.frame=self.bounds;
        
        _background.layer.mask=_gradient;
    }
    else
    {
        _background.layer.mask=nil;
    }
    
    
    //清空原有控件
    for(UIView *view in _content.subviews)
    {
        [view removeFromSuperview];
    }
    
    [_labels clear];
    self.labels=nil;
    
    //加载数据
    if(_dataArray && _dataArray.length>0)
    {
        self.labels=[KATArray arrayWithCapacity:_dataArray.length];
        
        double px=_margin;//x坐标
        
        for(int i=0;i<_dataArray.length;i++)
        {
            KATLabelBarData *data=_dataArray[i];
            data.num=i;
            
            KATLabel *label=[KATLabel labelWithFrame:RECT(0, 0, 0, 0) andStyle:_defaultStyle];
            label.text=data.text;
            label.tag=i;
            
            [label resizeFrame];
            
            label.frame=RECT(px, (_content.bounds.size.height-label.bounds.size.height)/2.0, label.bounds.size.width, label.bounds.size.height);
            
            UITapGestureRecognizer *tap=[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTaped:)] autorelease];
            [label addGestureRecognizer:tap];
            
            px+=label.bounds.size.width+_padding;
            
            [_labels put:label];
            [_content addSubview:label];
        }
        
        _content.contentSize=SIZE(px-_padding+_margin, _content.bounds.size.height);
    }
    else
    {
        _content.contentSize=self.bounds.size;
    }
    
    
    //指示器
    if(_indicator)
    {
        _indicator.position=POINT(_content.contentSize.width/2.0, _indicatorPositionY);
    }
    
    //更新数据
    [self updateData];
}


//加载数据(加载数据后更新控件)
- (void)loadData:(KATArray<KATLabelBarData *> *)dataArray
{
    self.dataArray=dataArray;
}


//更新数据
- (void)updateData
{
    //标签
    double px=_margin;//x坐标
    
    for(int i=0;i<_labels.length;i++)
    {
        KATLabel *label=_labels[i];
        label.frame=CGRectZero;//置零后重新计算
        
        int index=(int)label.tag;
        
        KATLabelBarData *data=_dataArray[index];
        
        if(index==_selectedIndex)//选中的
        {
            if(data.style)//有默认的样式
            {
                label.style=data.style;
            }
            else
            {
                label.style=_selectedStyle;
            }
        }
        else
        {
            if(label.style!=_defaultStyle)
            {
                label.style=_defaultStyle;
            }
        }
        
        [label resizeFrame];
        
        label.frame=RECT(px, (_content.bounds.size.height-label.bounds.size.height)/2.0, label.bounds.size.width, label.bounds.size.height);
        
        px+=label.bounds.size.width+_padding;
    }
    
    _content.contentSize=SIZE(px-_padding+_margin, _content.bounds.size.height);
    
    
    //位置调整
    if(_content.contentSize.width>_content.bounds.size.width)
    {
        //选中的label
        KATLabel *label=_labels[_selectedIndex];
        
        if(label)
        {
//            if(label.frame.origin.x-_margin<_content.contentOffset.x)//左边调整
//            {
//                [_content setContentOffset:POINT(label.frame.origin.x-_margin, 0) animated:(_slidingDuration>0)];
//            }
//            else if((label.frame.origin.x+label.frame.size.width+_margin)-_content.bounds.size.width>_content.contentOffset.x)//右边调整
//            {
//                [_content setContentOffset:POINT((label.frame.origin.x+label.frame.size.width+_margin)-_content.bounds.size.width, 0) animated:(_slidingDuration>0)];
//            }
            
            //调整到中点
            double px=label.center.x-_content.bounds.size.width/2.0;
            
            if(px<0)
            {
                px=0;
            }
            
            if(px>_content.contentSize.width-_content.bounds.size.width)
            {
                px=_content.contentSize.width-_content.bounds.size.width;
            }
            
            [_content setContentOffset:POINT(px, 0) animated:(_slidingDuration>0)];
        }
    }
    
    
    //指示器
    if(_indicator)
    {
        //选中的数据
        KATLabelBarData *data=self.selectedData;
        
        //选中的label
        KATLabel *label=_labels[_selectedIndex];
        
        if(data && label)
        {
            _indicator.hidden=NO;
            
            if(data.color)
            {
                _indicator.strokeColor=data.color.CGColor;
                
                if(_isFilledIndicator)//填充
                {
                    _indicator.fillColor=data.color.CGColor;
                }
            }
            else//默认颜色
            {
                _indicator.strokeColor=_selectedColor.CGColor;
                
                if(_isFilledIndicator)//填充
                {
                    _indicator.fillColor=_selectedColor.CGColor;
                }
            }
            
            //移动位置
            [_indicator clearAnimations];
            
            if(_slidingDuration>0)//有动画效果
            {
                [_indicator moveToPosition:POINT(label.center.x, _indicatorPositionY) withDuration:_slidingDuration];
            }
            else
            {
                _indicator.position=POINT(label.center.x, _indicatorPositionY);
            }
        }
        else
        {
            _indicator.hidden=YES;
        }
    }
}


//通过index设置选中的标签
- (void)selectWithIndex:(int)index
{
    if(index!=_selectedIndex && index>=0 && index<_dataArray.length)
    {
        _selectedIndex=index;
        
        //更新数据
        [self updateData];
        
        
        //回调
        if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(labelBar:didSelectWithData:)])
        {
            [_eventDelegate labelBar:self didSelectWithData:_dataArray[index]];
        }
    }
}


//通过data设置选中的标签
- (void)selectedWithData:(KATLabelBarData *)data
{
    int index=[_dataArray indexWithMember:data];
    
    if(index>=0)
    {
        [self selectWithIndex:index];
    }
}


//标签点击
- (void)labelTaped:(UIGestureRecognizer *)recognizer
{
    int index=(int)recognizer.view.tag;
    
    [self selectWithIndex:index];
}



//释放内存
- (void)dealloc
{
    [_indicator release];
    [_defaultStyle release];
    [_selectedColor release];
    [_dataArray release];
    [_content release];
    [_labels release];
    [_gradient release];
    [_background release];
    [_selectedStyle release];
    
    [super dealloc];
}


@end
